﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using NC.Infrastructure;
using NC.Infrastructure.Data;
using NC.Service.ApiRecord;
using NC.Service.Apply;
using NC.Service.CatchManager;
using NC.Service.ContentParams;
using NC.Service.Person;
using NC.Service.Target;

namespace NC.Web
{
    public class AutofacConfig
    {
        /// <summary>
        /// Autofac的注入服务
        /// </summary>
        public static void Config()
        {
            ContainerBuilder builder=new ContainerBuilder();

            //注册MVC WebApi
            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            //这里提供注册实际ApiController类型
            builder.RegisterApiControllers();
            builder.RegisterType<NCDbContext>().InstancePerLifetimeScope();
            builder.RegisterType<NCDbContext>().As<IUnitOfWork>().InstancePerLifetimeScope();
            //注册泛型仓储类型
            builder.RegisterGeneric(typeof (BaseRepository<>)).As(typeof (IRepository<>)).InstancePerLifetimeScope(); 

            RegisterService(builder);
            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

        /// <summary>
        /// 注册服务类
        /// </summary>
        /// <param name="builder"></param>
        private static void RegisterService(ContainerBuilder builder)
        {
            builder.RegisterType<PersonService>().As<IPersonService>().InstancePerLifetimeScope();
            builder.RegisterType<ApplyService>().As<IApplyService>().InstancePerLifetimeScope();
            builder.RegisterType<ApiRecordService>().As<IApiRecordService>().InstancePerLifetimeScope();
            builder.RegisterType<TargetService>().As<ITargetService>().InstancePerLifetimeScope();


            //注册缓存单例服务
            builder.RegisterType<CatchService>().As<ICatchService>().InstancePerLifetimeScope();
            builder.RegisterType<ContentParamsService>().As<IContentParamsService>().InstancePerLifetimeScope();
        }
    }
}